package cn.qu.phizline.webserver.event.handle.init;

import cn.qu.phizline.event.common.ResponseEvent;
import cn.qu.phizline.event.init.InitEvent;
import cn.qu.phizline.webserver.common.WebXRsa;
import cn.qu.phizline.webserver.event.handle.Handle;
import cn.qu.phizline.webserver.module.key.entity.Key;
import cn.qu.phizline.webserver.module.key.entity.KeyExample;
import cn.qu.phizline.webserver.module.key.mapper.KeyMapper;
import cn.qu.phizline.webserver.ws.WebServer;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;

/**
 * Created by zh on 2017/9/22.
 */
public class InitHandle implements Handle<InitEvent, ResponseEvent> {

    @Autowired
    private KeyMapper keyMapper;

    @Override
    public ResponseEvent handle(InitEvent payload) {
        InitEvent.InitBody body = (InitEvent.InitBody) payload.getBody();
        final String deviceId = body.getDeviceId();
/*
        List<Key> keyList = keyMapper.selectByExample(new KeyExample() {
            {
                createCriteria().andDeviceIdEqualTo(deviceId);
            }
        });

        Key key = null;
        if (!keyList.isEmpty()) {
            key = keyList.get(0);
        } else {
            key = new Key();
            key.setDeviceId(deviceId);

            Map<String, String> rsaKey = new WebXRsa().createKeys(1024);
            key.setServerPublishKey(rsaKey.get("publicKey"));
            key.setServerPrivateKey(rsaKey.get("privateKey"));

            keyMapper.insert(key);
        }

        return ResponseEvent.build(WebServer.getPayloadKey(payload.getType(), payload.getVersion()), InitEvent.CODE_SUCCESS, key.getServerPublishKey());
        */
        return ResponseEvent.build(WebServer.getPayloadKey(payload.getType(), payload.getVersion()), InitEvent.CODE_FAILURE, "publishKey");
    }

}
